package com.hehe.controller;


import com.hehe.Dao.Insert_Mapper;
import com.hehe.POJO.Tb_sql_test;
import com.hehe.Tools.Save_img_inverse;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class BatchUploads {

    @Value("${file.upload.path}")
    private String path;

    @Autowired(required = false)
    private Insert_Mapper insert_mapper;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");

    /*
    <form  method="post"   action="/upload2"  enctype="multipart/form-data">
        <input type="file" name="uploadFiles" value="请选择文件" multiple>
        <input type="submit" value="上传">
    </form>
     */


    //  将 MultipartFile  对象转换为  BufferedImage
    public static BufferedImage convert_to_BufferedImage(MultipartFile multipartFile) throws IOException {
        byte[] bytes = multipartFile.getBytes();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        return ImageIO.read(byteArrayInputStream);
    }


    //   @RequestParam("uploadFiles") List<MultipartFile> uploadFiles, @RequestBody PostObj postObj
    @RequestMapping("/upload_ajax_with_text")
    public String uploadFiles(@RequestParam("uploadFiles") MultipartFile[] uploadFiles, String params, HttpServletRequest request) throws JSONException {
        JSONObject jsonobj = new JSONObject(params);
        System.out.println("jsonobj.get(\"text1\") = " + jsonobj.get("title"));
        System.out.println("jsonobj.get(\"text2\") = " + jsonobj.get("describe"));

        System.out.println("postObj = " + uploadFiles);
//        JSONObject jsonObject = new JSONObject(String.valueOf(files));
//        JSONObject data = (JSONObject) jsonobj.get("ROOT");

        String currentDirectory = System.getProperty("user.dir");
        System.out.println("当前目录路径：" + currentDirectory);  // 当前目录路径：C:\Users\yxb\Desktop\SQL_STUDY
        currentDirectory = currentDirectory + "\\" + "SQL_IMG\\";
        System.out.println("currentDirectory = " + currentDirectory);

        ArrayList<String> list = new ArrayList<>();  // 存储生成的访问路径
        StringBuilder img_urls = new StringBuilder();
        if (uploadFiles.length > 0) {
            /*
            title:title__,
            page_url:page_url__,
            level:level__,
            describe:describe__,
            sql:test_sql__,
            answer:answer__,
             */

            Tb_sql_test tb_sql_test = new Tb_sql_test();
            try {
                for (int i = 0; i < uploadFiles.length; i++) {
                    MultipartFile uploadFile = uploadFiles[i];
                    //设置上传文件的位置在该项目目录下的uploadFile文件夹下，并根据上传的文件日期，进行分类保存
//                String format = sdf.format(new Date()); //  format = 2023/11/11/
                    File folder = new File(currentDirectory);
                    if (!folder.isDirectory()) {
                        folder.mkdirs();
                    }
                    String oldName = uploadFile.getOriginalFilename();
                    System.out.println("oldName = " + oldName);
                    String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
                    System.out.println("newName = " + newName);
                    try {
                        //currentDirectory = C:\Users\yxb\Desktop\sql-study\SQL_IMG\
                        //oldName = {1E90A983-55FE-4B7C-9D28-D33916DE7AB4}.png
                        //newName = f752771f-13a4-428e-bfdf-28966e6fa104.png

                        String full_name = currentDirectory + newName;
                        System.out.println("full_name = " + full_name);

                        // 保存 image 文件
//                      uploadFile.transferTo(new File(folder, newName));    // 这个保存图片的方法 已经废除
                        BufferedImage bufferedImage_data;
                        bufferedImage_data = convert_to_BufferedImage(uploadFile);
                        Save_img_inverse save_img_inverse = new Save_img_inverse();
                        bufferedImage_data = save_img_inverse.img_inverse(bufferedImage_data);
                        save_img_inverse.img2file(bufferedImage_data, "jpg", full_name);  //生成图片
                        //生成上传文件的访问路径
//                    request.getScheme() = http
//                    request.getServerName() = 172.20.10.10
//                    request.getServerPort() = 8054
                        String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/SQL_IMG/" + newName;
                        System.out.println("filePath = " + filePath);
                        list.add(filePath);
                        img_urls.insert(0, newName + " , ");
                    } catch (IOException e) {
                        e.printStackTrace();
                        return "false";
                    }
                }
                tb_sql_test.setLevel(jsonobj.get("level").toString());
                tb_sql_test.setTitle(jsonobj.get("title").toString());
                tb_sql_test.setPage_url(jsonobj.get("page_url").toString());
                tb_sql_test.setDescribe(jsonobj.get("describe").toString());
                tb_sql_test.setImg_urls(img_urls.toString());
                tb_sql_test.setAnswer(jsonobj.get("answer").toString());
                tb_sql_test.setSql(jsonobj.get("sql").toString());
                insert_mapper.insert__(tb_sql_test);
            }catch (Exception e){
                deleteFile(img_urls);
                return "false";
            }
            return "insert_success";
        } else {
            return "false";
        }
    }

    public void deleteFile(StringBuilder names){
        String[] file_name_listtt = names.toString().split(",");
        for (String file_name : file_name_listtt) {
            if (file_name.trim().length() > 5){
                System.out.println(file_name);
                // 指定要删除的文件路径
                String filePath = path + "\\" + file_name.trim();
                System.out.println("删除文件 : " + filePath);
                // 创建一个File对象
                File file = new File(filePath);
                // 调用delete()方法删除文件
                if (file.delete()) {
                    System.out.println("文件删除成功");
                } else {
                    System.out.println("文件删除失败");
                }
            }
        }




    }

    @RequestMapping("/upload_image")
    public String upload(MultipartFile[] uploadFiles, HttpServletRequest request) {

        return "";
    }
}

